'use client';

import React, { useState, useMemo } from 'react';
import {
  ComposedChart,
  Bar,
  Line,
  XAxis,
  YAxis,
  ResponsiveContainer,
  Tooltip,
  Cell,
} from 'recharts';
import { useMarketData } from '../hooks/useMarketData';

interface SimpleTradingViewChartProps {
  symbol: string;
}

interface CandleData {
  time: number;
  open: number;
  high: number;
  low: number;
  close: number;
  volume: number;
}

interface ProcessedCandleData extends CandleData {
  timeStr: string;
  bodyHeight: number;
  bodyTop: number;
  isGreen: boolean;
  wickHigh: number;
  wickLow: number;
  bodyColor: string;
  wickColor: string;
}

export default function SimpleTradingViewChart({ symbol }: SimpleTradingViewChartProps) {
  const [timeframe, setTimeframe] = useState('4h');
  const [showVolume, setShowVolume] = useState(true);

  // 使用币安真实数据
  const { klineData, loading: dataLoading } = useMarketData({
    symbol: symbol.replace('/', ''),  // BTC/USDT -> BTCUSDT
    interval: timeframe,
    dataSource: 'binance',
    enableRealtime: false
  });

  // 处理K线数据
  const processedData = useMemo(() => {
    if (!klineData || klineData.length === 0) return [];

    return klineData.map((candle): ProcessedCandleData => {
      const isGreen = candle.close > candle.open;
      const bodyTop = Math.max(candle.open, candle.close);
      const bodyHeight = Math.abs(candle.close - candle.open);
      
      return {
        ...candle,
        timeStr: new Date(candle.time).toLocaleTimeString('zh-CN', {
          hour: '2-digit',
          minute: '2-digit',
          month: '2-digit',
          day: '2-digit',
        }),
        bodyHeight,
        bodyTop,
        isGreen,
        wickHigh: candle.high,
        wickLow: candle.low,
        bodyColor: isGreen ? '#02C076' : '#F6465D',
        wickColor: isGreen ? '#02C076' : '#F6465D',
      };
    });
  }, [klineData]);

  // 时间周期选项
  const timeframes = [
    { label: '1m', value: '1m' },
    { label: '5m', value: '5m' },
    { label: '15m', value: '15m' },
    { label: '1h', value: '1h' },
    { label: '4h', value: '4h' },
    { label: '1d', value: '1d' },
    { label: '1w', value: '1w' },
  ];

  // 自定义提示框
  const CustomTooltip = ({ active, payload, label }: {
    active?: boolean;
    payload?: Array<{payload: ProcessedCandleData}>;
    label?: string;
  }) => {
    if (active && payload && payload.length) {
      const data = payload[0].payload as ProcessedCandleData;
      return (
        <div className="bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-lg p-3 shadow-lg">
          <p className="text-gray-900 dark:text-white font-medium">{label}</p>
          <div className="grid grid-cols-2 gap-2 mt-2 text-sm">
            <div>
              <span className="text-gray-500 dark:text-gray-400">开盘: </span>
              <span className="text-gray-900 dark:text-white">${data.open.toFixed(2)}</span>
            </div>
            <div>
              <span className="text-gray-500 dark:text-gray-400">收盘: </span>
              <span className={data.isGreen ? 'text-green-600' : 'text-red-600'}>
                ${data.close.toFixed(2)}
              </span>
            </div>
            <div>
              <span className="text-gray-500 dark:text-gray-400">最高: </span>
              <span className="text-gray-900 dark:text-white">${data.high.toFixed(2)}</span>
            </div>
            <div>
              <span className="text-gray-500 dark:text-gray-400">最低: </span>
              <span className="text-gray-900 dark:text-white">${data.low.toFixed(2)}</span>
            </div>
            <div className="col-span-2">
              <span className="text-gray-500 dark:text-gray-400">成交量: </span>
              <span className="text-gray-900 dark:text-white">
                {data.volume.toLocaleString()}
              </span>
            </div>
          </div>
        </div>
      );
    }
    return null;
  };

  return (
    <div className="bg-white dark:bg-gray-800 rounded-lg shadow-sm border border-gray-200 dark:border-gray-700 h-full flex flex-col">
      {/* 图表工具栏 */}
      <div className="flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700">
        <div className="flex items-center space-x-4">
          <h3 className="font-semibold text-gray-900 dark:text-white">
            K线图表
          </h3>
          <div className="flex items-center space-x-1 text-sm text-gray-600 dark:text-gray-400">
            <span>当前周期: {timeframe}</span>
            <span>|</span>
            <span>交易对: {symbol}</span>
          </div>
        </div>

        {/* 工具按钮 */}
        <div className="flex items-center space-x-2">
          {/* 时间周期选择器 */}
          <div className="flex items-center space-x-1">
            {timeframes.map((tf) => (
              <button
                key={tf.value}
                onClick={() => setTimeframe(tf.value)}
                className={`px-3 py-1 text-sm rounded transition-colors ${
                  timeframe === tf.value
                    ? 'bg-blue-500 text-white'
                    : 'bg-gray-100 text-gray-600 hover:bg-gray-200 dark:bg-gray-700 dark:text-gray-400 dark:hover:bg-gray-600'
                }`}
              >
                {tf.label}
              </button>
            ))}
          </div>

          {/* 成交量切换 */}
          <button
            onClick={() => setShowVolume(!showVolume)}
            className={`px-3 py-1 text-sm rounded transition-colors ${
              showVolume
                ? 'bg-green-500 text-white'
                : 'bg-gray-100 text-gray-600 hover:bg-gray-200 dark:bg-gray-700 dark:text-gray-400 dark:hover:bg-gray-600'
            }`}
          >
            成交量
          </button>
        </div>
      </div>

      {/* 图表容器 */}
      <div className="flex-1 relative">
        {dataLoading && (
          <div className="absolute inset-0 flex items-center justify-center bg-white/80 dark:bg-gray-800/80 z-10">
            <div className="flex items-center space-x-2">
              <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-blue-500"></div>
              <span className="text-gray-600 dark:text-gray-400">加载图表数据...</span>
            </div>
          </div>
        )}
        
        <div className="p-4 h-full">
          <ResponsiveContainer width="100%" height="100%">
            <ComposedChart data={processedData} margin={{ top: 20, right: 30, left: 20, bottom: 5 }}>
              <XAxis 
                dataKey="timeStr" 
                axisLine={false}
                tickLine={false}
                tick={{ fontSize: 12, fill: '#666' }}
              />
              <YAxis 
                domain={['dataMin - 100', 'dataMax + 100']}
                axisLine={false}
                tickLine={false}
                tick={{ fontSize: 12, fill: '#666' }}
                width={80}
              />
              {/* 成交量专用的Y轴 */}
              {showVolume && (
                <YAxis 
                  yAxisId="volume"
                  orientation="right"
                  domain={[0, 'dataMax']}
                  axisLine={false}
                  tickLine={false}
                  tick={{ fontSize: 10, fill: '#666' }}
                  width={60}
                />
              )}
              <Tooltip content={<CustomTooltip />} />
              
              {/* K线数据线 */}
              <Line
                type="monotone"
                dataKey="close"
                stroke="transparent"
                dot={false}
                strokeWidth={0}
              />
              
              {/* 成交量 */}
              {showVolume && (
                <Bar 
                  dataKey="volume" 
                  yAxisId="volume"
                  opacity={0.3}
                >
                  {processedData.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={entry.bodyColor} />
                  ))}
                </Bar>
              )}
            </ComposedChart>
          </ResponsiveContainer>
        </div>
      </div>

      {/* 图表说明 */}
      <div className="p-3 border-t border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-750">
        <div className="flex items-center justify-between text-xs text-gray-500 dark:text-gray-400">
          <div className="flex items-center space-x-4">
            <div className="flex items-center space-x-1">
              <div className="w-3 h-3 bg-green-500 rounded"></div>
              <span>涨幅</span>
            </div>
            <div className="flex items-center space-x-1">
              <div className="w-3 h-3 bg-red-500 rounded"></div>
              <span>跌幅</span>
            </div>
          </div>
          <div className="text-right">
            <span>币安实时K线数据</span>
          </div>
        </div>
      </div>
    </div>
  );
}
